package com.tongjie.hotelbooking.security.user;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.tongjie.hotelbooking.user.enums.UserType;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CurrentUserInfo implements UserDetails, Serializable {

    private static final long serialVersionUID = -1978387076760623434L;

    private Long id;
    private String name;
    private String username;
    private String nickName;
    private String password;
    private String avatar;
    private Integer status;
    private String telephone;
    private String lastLoginIp;
    private Long lastLoginTime;
    private String creatorId;
    private Long createTime;
    private Integer deleted;
    private String roleId;

    private String mobile;
    private String wxOpenId;
    private UserType userType;

    private CurrentUserRole role;

    @JsonIgnore
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        if (this.role == null) {
            return simpleGrantedAuthorities;
        }

        for (CurrentUserPermission currentUserPermission : role.getPermissions()) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(currentUserPermission.getPermissionId()));
            for (CurrentUserAction currentUserAction : currentUserPermission.getActionEntitySet()) {
                simpleGrantedAuthorities.add(new SimpleGrantedAuthority(currentUserAction.getAction()));
            }
        }

        return simpleGrantedAuthorities;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
